package com.abgame.test.javase.demo;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.format.DateTimeFormatter;
import java.util.*;
 public class RandomWeekGrouping {
    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2022, 1, 1);
        LocalDate endDate = LocalDate.of(2022, 1, 31);
         Map<Integer, List<LocalDate>> weekGroups = groupRandomDatesByWeek(startDate, endDate);
        for (Map.Entry<Integer, List<LocalDate>> entry : weekGroups.entrySet()) {
            int weekNumber = entry.getKey();
            List<LocalDate> weekDates = entry.getValue();
            LocalDate weekStartDate = weekDates.get(0);
            LocalDate weekEndDate = weekDates.get(weekDates.size() - 1);
             System.out.println("Week " + weekNumber + " (" + weekStartDate + " - " + weekEndDate + "):");
            System.out.println("Grouping Information: " + weekDates);
            System.out.println();
        }
    }
     public static Map<Integer, List<LocalDate>> groupRandomDatesByWeek(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> dates = new ArrayList<>();
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            dates.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }
         int halfSize = dates.size() / 2;
        List<LocalDate> randomDates = new ArrayList<>();
        Random random = new Random();
        while (randomDates.size() < halfSize) {
            int index = random.nextInt(dates.size());
            LocalDate date = dates.get(index);
            if (!randomDates.contains(date)) {
                randomDates.add(date);
            }
        }
         Collections.sort(randomDates); // Sort the random dates in ascending order
         Map<Integer, List<LocalDate>> weekGroups = new HashMap<>();
        int weekNumber = 1;
        List<LocalDate> currentWeek = new ArrayList<>();
         for (LocalDate date : randomDates) {
            currentWeek.add(date);
             if (date.getDayOfWeek() == DayOfWeek.SUNDAY || date == randomDates.get(randomDates.size() - 1)) {
                weekGroups.put(weekNumber, new ArrayList<>(currentWeek));
                currentWeek.clear();
                weekNumber++;
            }
        }
         return weekGroups;
    }
}